package classifiers;

import mulan.classifier.InvalidDataException;
import mulan.classifier.MultiLabelLearner;
import mulan.data.InvalidDataFormatException;
import mulan.data.MultiLabelInstances;
import utils.TagCluster;
import utils.TagClustering;
import utils.Utils;
import weka.core.SerializationHelper;

public class TwoLevelClassifierBuilder {

	private String input_directory,output_directory;
	private TagClustering tc;
	private DatasetDescription level_one_description,level_two_description;
	private TwoLevelClassifier classifier;
	
	public TwoLevelClassifierBuilder(String input_directory,
			String output_directory, TagClustering tc,
			DatasetDescription level_one_description,
			DatasetDescription level_two_description) {
		this.input_directory = input_directory;
		this.output_directory = output_directory;
		this.tc = tc;
		this.level_one_description = level_one_description;
		this.level_two_description = level_two_description;
	}
	
	public void buildAndSaveAllClassifiers() {
		buildLevelOne();
		buildLevelTwo();
	}

	private void buildLevelTwo() {
		for ( TagCluster cluster : tc.getAllClusters() ) {
			String file_name = Utils.getNameForLevelTwo(level_two_description, cluster);
			try {
				MultiLabelInstances train = new MultiLabelInstances(input_directory+file_name+".arff", Utils.getXML(false,cluster.toString()));
				MultiLabelLearner learner = classifier.getLevelTwoClassifierForCluster(tc.getClusterIdx(cluster.toString()));
				learner.build(train);
				SerializationHelper.write(output_directory+file_name+".model",learner);
			} catch (InvalidDataFormatException e) {
				e.printStackTrace();
			} catch (InvalidDataException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void buildLevelOne() {
		String file_name = Utils.getNameForLevelOne(level_one_description);
		try {
			MultiLabelInstances train = new MultiLabelInstances(input_directory+file_name+".arff", Utils.getXML(true, ""));
			classifier.getLevel_one_classifier().build(train);
			SerializationHelper.write(output_directory+file_name+".model", classifier.getLevel_one_classifier());
		} catch (InvalidDataFormatException e) {
			e.printStackTrace();
		} catch (InvalidDataException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
